//
//  JKBaseCode.m
//  JKThreadTest
//
//  Created by 王冲 on 2018/10/24.
//  Copyright © 2018年 JK科技有限公司. All rights reserved.
//

#import "JKBaseCode.h"

@interface JKBaseCode()

/**
 票的数量
 */
@property(nonatomic,assign) int ticketCount;

/**
 钱的数量
 */
@property(nonatomic,assign) int moneyCount;

@end

@implementation JKBaseCode

- (void)otherTest {}

#pragma mark 9.取钱存钱的测试(多线程安全的隐患)
-(void)moneyTest{
    
    self.moneyCount = 100;
    
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    dispatch_async(queue, ^{
        
        NSLog(@"1的优先级-----%g  - %@",[[NSThread currentThread] threadPriority],[NSThread currentThread]);
        
        for (int i = 0; i<5; i++) {
            
            // 存钱
            [self __saveMoney];
        }
    });
    
    dispatch_async(queue, ^{
        
        NSLog(@"2的优先级-----%g  - %@",[[NSThread currentThread] threadPriority],[NSThread currentThread]);
        
        for (int i = 0; i<5; i++) {
            
            // 取钱
            [self __drawMoney];
        }
    });
}

// 存钱
-(void)__saveMoney{
    
    int oldMoney = self.moneyCount;
    sleep(0.2);
    oldMoney = oldMoney + 50;
    self.moneyCount = oldMoney;
    
    NSLog(@"存进去50元，余额是%d - %@",oldMoney,[NSThread currentThread]);

}

// 取钱
-(void)__drawMoney{
    
    int oldMoney = self.moneyCount;
    sleep(0.2);
    oldMoney = oldMoney - 30;
    self.moneyCount = oldMoney;
    
    NSLog(@"花去20元，余额是%d - %@",oldMoney,[NSThread currentThread]);
}

#pragma mark 8.买票的测试(多线程安全的隐患)
-(void)ticketTest{
    
    self.ticketCount = 15;
    
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    dispatch_async(queue, ^{
        
        for (int i = 0; i<5; i++) {
            
            [self __buyTicket];
        }
    });
    
    dispatch_async(queue, ^{
        
        for (int i = 0; i<5; i++) {
            
            [self __buyTicket];
        }
    });
    
    dispatch_async(queue, ^{
        
        for (int i = 0; i<5; i++) {
            
            [self __buyTicket];
        }
    });
}

-(void)__buyTicket{

    int oldTickCount = self.ticketCount;
    sleep(.2);
    oldTickCount --;
    self.ticketCount = oldTickCount;
    
    NSLog(@"还有%d张票-%@",oldTickCount,[NSThread currentThread]);

}


@end
